package com.huishen.edrivenew.ui;


import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.huishen.edrivenew.AppContext;
import com.huishen.edrivenew.AppManager;
import com.huishen.edrivenew.Constants;
import com.huishen.edrivenew.R;
import com.huishen.edrivenew.bean.CoachBean;
import com.huishen.edrivenew.bean.DateBean;
import com.huishen.edrivenew.bean.ListLessonInfoBean;
import com.huishen.edrivenew.bean.OutlineBean;
import com.huishen.edrivenew.bean.SchoolBean;
import com.huishen.edrivenew.bean.StudentBean;
import com.huishen.edrivenew.net.BitmapManager;
import com.huishen.edrivenew.net.JsonResponseHandler;
import com.huishen.edrivenew.net.NetApi;
import com.huishen.edrivenew.util.FileUtil;
import com.huishen.edrivenew.util.ImageUtils;
import com.huishen.edrivenew.util.StringUtils;
import com.huishen.edrivenew.util.TLog;
import com.huishen.edrivenew.widget.CalendarFragment;
import com.huishen.edrivenew.widget.CircleImageView;
import com.huishen.edrivenew.widget.LoadingDialog;
import com.huishen.edrivenew.widget.SelectDialog;

/**
 * 主页面
 * 
 * @author wu
 * @version 2015/7/4.
 */
public class MainActivity extends FragmentActivity {

    private DrawerLayout drawerLayout;
    private ImageButton header_menu;
    private ImageButton msg;
    private View vCenterLayout;// 个人中心

    private CircleImageView headView;
    private TextView cen_name;
    private TextView cen_phone;
    private TextView cen_time;
    private TextView cen_dist;
    private TextView cen_money;
    private View vjudge;
    private View vlist;
    private View vsetting;
    private View center_detial;


    private View vSchool;
    private View vCoach;

    private CircleImageView coachHead;
    private CircleImageView schoolHead;

    private TextView coachName;
    private TextView coachCar;
    private TextView coachCarNumber;

    private TextView schoolName;
    private TextView schoolAddress;

    private View vLogLayout;

    // 培训日志
    private TextView tx_log;

    // 是约驾校还是约教练 新模式或者旧模式
    private boolean isSchool = false;

    // 教练id
    private int cohId;

    // 拍照相关
    CharSequence[] items = new CharSequence[] {"手机相册", "手机拍照"};
    private String theLarge, theThumbnail;
    private File imgFile;

    BitmapManager bmpManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        TLog.log("onCreate onCreate");
        
        AppManager.getInstance().addActivity(this);

        setContentView(R.layout.activity_main);
        AppContext.getInstance().mainActivity = this;

        if (AppContext.getInstance().studentBean == null) {
            AppContext.getInstance().getStudent();
        }

        isSchool = AppContext.getInstance().studentBean.getIsSchool();
        cohId = AppContext.getInstance().studentBean.coachId;

        initView();
        setOnClick();

        initDate();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        TLog.log("onNewIntent");
        super.onNewIntent(intent);
    }


    private void initView() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
        vCenterLayout = findViewById(R.id.drawerMenu);
        header_menu = (ImageButton) findViewById(R.id.header_menu);
        msg = (ImageButton) findViewById(R.id.main_btn_msg);

        vSchool = findViewById(R.id.f_app_school);
        vCoach = findViewById(R.id.f_app_coach);

        tx_log = (TextView) findViewById(R.id.log_text);
        vLogLayout = findViewById(R.id.train_log_layout);

        coachHead = (CircleImageView) findViewById(R.id.f_appoint_photo);
        schoolHead = (CircleImageView) findViewById(R.id.f_appoint_school_photo);

        coachName = (TextView) findViewById(R.id.f_appoint_coachname);
        coachCar = (TextView) findViewById(R.id.f_appoint_coachcar);
        coachCarNumber = (TextView) findViewById(R.id.f_appoint_carnum);

        schoolName = (TextView) findViewById(R.id.f_appoint_schoolname);
        schoolAddress = (TextView) findViewById(R.id.f_appoint_schoolname2);
        headView = (CircleImageView) findViewById(R.id.center_photo);
        cen_name = (TextView) findViewById(R.id.center_name);
        cen_phone = (TextView) findViewById(R.id.center_tel);
        cen_time = (TextView) findViewById(R.id.center_time);
        cen_dist = (TextView) findViewById(R.id.center_dis);
        cen_money = (TextView) findViewById(R.id.center_money);
        vjudge = findViewById(R.id.menu_pro);
        vlist = findViewById(R.id.menu_info);
        vsetting = findViewById(R.id.menu_hospital);
        center_detial = findViewById(R.id.center_detial);

        if (isSchool) {
            vSchool.setVisibility(View.VISIBLE);
            vCoach.setVisibility(View.GONE);

            tx_log.setText(Constants.T_LOG_SCHOOL);
        } else {
            vSchool.setVisibility(View.GONE);
            vCoach.setVisibility(View.VISIBLE);
            tx_log.setText(Constants.T_LOG_COACH);
            // 隐藏个人中心余额信息
            center_detial.setVisibility(View.GONE);
        }

        setCalendar();

        vsetting.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(it);
            }
        });
    }


    private void initDate() {
        showDialog();
        getOutline();
    }


    private void setDate() {
        if (isSchool) {
            SchoolBean bean = AppContext.getInstance()._7DaysInfo.schoolInfo;
            if (bean == null) {
                return;
            }
            schoolName.setText(bean.name);
            schoolAddress.setText(bean.addr);

            if (!StringUtils.isEmpty(bean.path)) {
                bmpManager =
                        new BitmapManager(BitmapFactory.decodeResource(AppContext.getInstance()
                                .getResources(), R.drawable.photo_bg_sc));
                bmpManager.loadBitmap(bean.path, coachHead);
            }

        } else {
            CoachBean bean = AppContext.getInstance()._7DaysInfo.cohInfo;
            if (bean == null) {
                return;
            }
            coachName.setText(bean.name);
            coachCar.setText(bean.carBrand);
            coachCarNumber.setText(bean.carNum);

            if (!StringUtils.isEmpty(bean.path)) {
                bmpManager =
                        new BitmapManager(BitmapFactory.decodeResource(AppContext.getInstance()
                                .getResources(), R.drawable.photo_bg_t));
                bmpManager.loadBitmap(bean.path, coachHead);
            }

        }
        cen_name = (TextView) findViewById(R.id.center_name);
        cen_phone = (TextView) findViewById(R.id.center_tel);
        cen_time = (TextView) findViewById(R.id.center_time);
        cen_dist = (TextView) findViewById(R.id.center_dis);
        cen_money = (TextView) findViewById(R.id.center_money);

        vjudge = findViewById(R.id.menu_pro);
        vlist = findViewById(R.id.menu_info);
        vsetting = findViewById(R.id.menu_hospital);

        StudentBean stubean = AppContext.getInstance().studentBean;
        cen_name.setText(stubean.name);
        cen_phone.setText(stubean.phone);
        cen_time.setText(stubean.timeNum + "");
        cen_dist.setText(stubean.distance + "");
        cen_money.setText(stubean.balance + "");

        // 设置头像
        if (!StringUtils.isEmpty(stubean.path)) {
            bmpManager =
                    new BitmapManager(BitmapFactory.decodeResource(AppContext.getInstance()
                            .getResources(), R.drawable.photo_bg));
            bmpManager.loadBitmap(stubean.path, headView);
        }

        vjudge.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSchool) {
                    AppContext.getInstance().classActivityType = 1;
                    Intent in = new Intent(MainActivity.this, ClassListSchoolActivity.class);
                    startActivity(in);
                } else {
                    Toast.makeText(MainActivity.this, "绑定教练没有此数据!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        vlist.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AppContext.getInstance().classActivityType = 2;
                if (isSchool) {
                    Intent in = new Intent(MainActivity.this, ClassListSchoolActivity.class);
                    startActivity(in);
                } else {
                    Intent in = new Intent(MainActivity.this, ClassListCoachActivity.class);
                    startActivity(in);
                }
            }
        });
        headView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                updateloadPhoto();
            }
        });
    }



    private void setCalendar() {
        FragmentManager fm = this.getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();

        CalendarFragment calendar = CalendarFragment.create();
        tx.replace(R.id.appointment_calendar, calendar);
        tx.commit();
    }


    private void setOnClick() {
        header_menu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                drawerLayout.openDrawer(vCenterLayout);
            }
        });
        msg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 消息页面
                // Intent in = new Intent(MainActivity.this,ListActivity.class);
                // in.putExtra(ListActivity.STATUS_KEY,ListActivity.STATUS_MSGLIST);
                // startActivity(in);
            }
        });
        vLogLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AppContext.getInstance().classActivityType = 0;
                if (isSchool) {
                    Intent in = new Intent(MainActivity.this, ClassListSchoolActivity.class);
                    startActivity(in);
                } else {
                    Intent in = new Intent(MainActivity.this, ClassListCoachActivity.class);
                    startActivity(in);
                }
            }
        });
    }

    public void updateloadPhoto() {
        Dialog imageDialog =
                new AlertDialog.Builder(this).setTitle("上传头像").setIcon(android.R.drawable.btn_star)
                        .setItems(items, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int item) {
                                // setClosable(dialog, false);
                                // 相册选图
                                goToSelectPicture(item);
                            }
                        }).create();
        imageDialog.show();
    }

    private void setClosable(DialogInterface dialog, boolean b) {
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 日历日期被点击
    public void onCaClick(DateBean bean) {
        if (isSchool) {
            caClickSchool(bean);
        } else {
            caClickCoach(bean);
        }
    }

    // 条转选择头像
    private void goToSelectPicture(int position) {
        switch (position) {
            case 0:
                Intent intent;
                if (Build.VERSION.SDK_INT < 19) {
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "选择图片"),
                            ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
                } else {
                    intent = new Intent(Intent.ACTION_PICK, Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "选择图片"),
                            ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
                }
                break;
            case 1:
                // 判断是否挂载了SD卡
                String savePath = "";
                String storageState = Environment.getExternalStorageState();
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    savePath =
                            Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + "/edrive/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }
                }

                // 没有挂载SD卡，无法保存文件
                if (StringUtils.isEmpty(savePath)) {
                    showToast("无法保存照片，请检查SD卡是否挂载");
                    return;
                }
                String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String fileName = "edrive_" + timeStamp + ".jpg";// 照片命名
                File out = new File(savePath, fileName);
                Uri uri = Uri.fromFile(out);

                theLarge = savePath + fileName;// 该照片的绝对路径

                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
                break;
            default:
                break;
        }
    }

    private void caClickSchool(final DateBean bean) {
        SelectDialog dialog = new SelectDialog(this, new SelectDialog.SelectDailogListener() {

            @Override
            public void onClickSelect(int select) {
                if (select > 0) {
                    AppContext.getInstance().dateBean = bean;
                    AppContext.getInstance().dateBean.type = select;

                    Intent it = new Intent(MainActivity.this, RequestCoachListActivity.class);
                    startActivity(it);
                }
            }
        });
        dialog.show();
    }

    private void caClickCoach(DateBean bean) {
        AppContext.getInstance().dateBean = bean;
        Intent it = new Intent(MainActivity.this, RequestCoachActivity.class);
        startActivity(it);
    }


    private void querySchoolDays() {
        NetApi.querySchoolLessonInfoById(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                ListLessonInfoBean bean =
                        (ListLessonInfoBean) ListLessonInfoBean.parseJson(jsonObj);
                AppContext.getInstance()._7DaysInfo = bean;
                DateBean.setState(AppContext.getInstance().days, bean);
                // 设置学校信息
                setDate();

                if (AppContext.getInstance().caAdapter != null) {
                    AppContext.getInstance().caAdapter.notifyDataSetChanged();
                }

                dismissDialog();
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("查询约课信息失败！");
            }

            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        });
    }

    private void queryCoachDays() {
        NetApi.queryStuCoachLessonInfo(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                ListLessonInfoBean bean =
                        (ListLessonInfoBean) ListLessonInfoBean.parseJson(jsonObj);
                TLog.log(bean.code + "");

                AppContext.getInstance()._7DaysInfo = bean;

                DateBean.setState(AppContext.getInstance().days, bean);

                // 设置教练信息
                setDate();

                if (AppContext.getInstance().caAdapter != null) {
                    TLog.log("notifyDataSetChanged");
                    AppContext.getInstance().caAdapter.notifyDataSetChanged();
                }

                dismissDialog();
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                dismissDialog();
                showToast("查询约课信息失败！");
            }

            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        }, cohId);
    }


    private void getOutline() {
        NetApi.queryStuTeachOutline(this, new JsonResponseHandler() {
            @Override
            public void onSuccess(int code, JSONObject jsonObj, Object[] args) {
                try {
                    if (code == Constants.N_SUCCESS) {
                        JSONObject jobj = jsonObj.getJSONObject("stuData");
                        OutlineBean bean = (OutlineBean) OutlineBean.parseJson(jobj);
                        AppContext.getInstance().outline = bean;
                        AppContext.getInstance().studentBean.balance = bean.money;

                    } else {
                        showToast("获取大纲信息失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("获取大纲信息失败");
                }
                if (isSchool) {
                    querySchoolDays();
                } else {
                    queryCoachDays();
                }
            }

            @Override
            public void onFailure(int code, String errorMessage, Object[] args) {
                showToast("获取大纲信息失败");
            }

            @Override
            public void onSessionFailure() {
                dismissDialog();
                super.onSessionFailure();
            }
        });
    }


    /** loading框和提示 **/
    public LoadingDialog dialog;

    public void showDialog() {
        if (dialog == null) {
            dialog = new LoadingDialog(this);
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    public void dismissDialog() {
        try {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        } catch (Exception e) {}
    }

    public void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }



    @Override
    public void onActivityResult(final int requestCode, final int resultCode,
            final Intent imageReturnIntent) {
        if (resultCode != Activity.RESULT_OK) return;
        TLog.log("onActivityResult OK");
       
        new Thread() {
            private String selectedImagePath;
            @Override
            public void run() {
                Bitmap bitmap = null;

                if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD) {
                    if (imageReturnIntent == null) return;
                    Uri selectedImageUri = imageReturnIntent.getData();
                    if (selectedImageUri != null) {
                        selectedImagePath =
                                ImageUtils.getImagePath(selectedImageUri, MainActivity.this);
                    }

                    if (selectedImagePath != null) {
                        theLarge = selectedImagePath;
                    } else {
                        bitmap =
                                ImageUtils.loadPicasaImageFromGalley(selectedImageUri,
                                        MainActivity.this);
                    }

                    if (AppContext.isMethodsCompat(android.os.Build.VERSION_CODES.ECLAIR_MR1)) {
                        String imaName = FileUtil.getFileName(theLarge);
                        if (imaName != null)
                            bitmap =
                                    ImageUtils.loadImgThumbnail(MainActivity.this, imaName,
                                            MediaStore.Images.Thumbnails.MICRO_KIND);
                    }
                    if (bitmap == null && !StringUtils.isEmpty(theLarge))
                        bitmap = ImageUtils.loadImgThumbnail(theLarge, 200, 200);
                } else if (requestCode == ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA) {
                    // 拍摄图片
                    if (bitmap == null && !StringUtils.isEmpty(theLarge)) {
                        bitmap = ImageUtils.loadImgThumbnail(theLarge, 200, 200);
                    }
                }

                if (bitmap != null) {// 存放照片的文件夹
                    String savePath =
                            Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + "/edrive/Camera/";
                    File savedir = new File(savePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }

                    String largeFileName = FileUtil.getFileName(theLarge);
                    String largeFilePath = savePath + largeFileName;
                    // 判断是否已存在缩略图
                    if (largeFileName.startsWith("thumb_") && new File(largeFilePath).exists()) {
                        theThumbnail = largeFilePath;
                        imgFile = new File(theThumbnail);
                    } else {
                        // 生成上传的800宽度图片
                        String thumbFileName = "thumb_" + largeFileName;
                        theThumbnail = savePath + thumbFileName;
                        if (new File(theThumbnail).exists()) {
                            imgFile = new File(theThumbnail);
                        } else {
                            try {
                                // 压缩上传的图片
                                ImageUtils.createImageThumbnail(MainActivity.this, theLarge,
                                        theThumbnail, 800, 80);
                                imgFile = new File(theThumbnail);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1 && msg.obj != null) {
                // 显示图片
                headView.setImageBitmap((Bitmap) msg.obj);
            }
        }
    };


}
